package com.ad.pet.app.main.desniger;

import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.design.widget.BottomSheetDialog;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.ad.pet.DaggerMainActivityCompent;
import com.ad.pet.MainActivity;
import com.ad.pet.MainActivityCompent;
import com.ad.pet.R;
import com.ad.pet.app.main.adapter.HomeViewPagerAdapter;
import com.ad.pet.app.main.desniger.adapter.DesnigerShopAdapter;
import com.ad.pet.common.data.injector.HasComponent;
import com.ad.pet.common.data.utils.DensityUtil;
import com.ad.pet.common.data.utils.ui.BottomSheetUtil;
import com.ad.pet.common.data.utils.ui.ToastUtil;
import com.ad.pet.common.structure.mvp.BasePresenter;
import com.ad.pet.common.structure.ui.activity.BaseActivity;
import com.ad.pet.models.remote.main.DesingerMain;
import com.ad.pet.models.remote.main.DesingerType;
import com.ad.pet.models.remote.type.LngLat;
import com.ad.pet.ui.loopview.LoopView;
import com.ad.pet.ui.loopview.entity.LoopViewEntity;
import com.ad.pet.utils.CoodinateCovertor;
import com.library.flowlayout.FlowLayoutManager;
import com.library.flowlayout.SpaceItemDecoration;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * Created by SEELE on 2019/6/27.
 */

public class DesnigerStoreActivity extends BaseActivity implements DesnigerContract.View, HasComponent<MainActivityCompent> {
    private BottomSheetDialog mPhotoDialog;
    private View mDialogView;
    private Button mButCancel;
    private Button mButOpen;
    private Button mButPhoto;

    @Inject
    DesnigerPresenter mDesnigerPresenter;
    @BindView(R.id.iv_head)
    LoopView iv_head;

    @BindView(R.id.tv_shop_name)
    TextView tvShopName;
    @BindView(R.id.tv_address)
    TextView tvAddress;
    @BindView(R.id.tv_time)
    TextView tvTime;
    @BindView(R.id.recycelr_service)
    RecyclerView recycelrService;
    @BindView(R.id.tab_layout)
    TabLayout tabLayout;
    @BindView(R.id.viewpager)
    ViewPager viewpager;
    @BindView(R.id.btn_chat)
    Button btnChat;


    @BindView(R.id.iv_back)
    ImageView mIvBack;
    DesingerMain desingerMain;
    private MainActivityCompent mMainComponent;

    private ArrayList<Fragment> mFragmentList;
    private HomeViewPagerAdapter mHomeViewPagerAdapter;
    private ArrayList<String> mList_title;

    @Override
    protected void initViews() {
        desingerMain = (DesingerMain) getIntent().getSerializableExtra("store");

        mDesnigerPresenter.onCreate(this);
        mDialogView = LayoutInflater.from(this).inflate(R.layout.layout_dialog_photo, null);
        mButCancel = mDialogView.findViewById(R.id.but_cancel);
        mButPhoto = mDialogView.findViewById(R.id.but_photo);
        mButOpen = mDialogView.findViewById(R.id.but_open);

        mButPhoto.setText("高德地图");
        mButOpen.setText("百度地图");
        mButOpen.setVisibility(View.GONE);
        mButPhoto.setVisibility(View.GONE);

        mPhotoDialog = new BottomSheetDialog(this);
        mPhotoDialog.setContentView(mDialogView);
        BottomSheetUtil.statusBarTranslucent(mPhotoDialog);

//        GlideUtil.load(mActivity,desingerMain.getShop_avatar(),iv_head);
        tvShopName.setText(desingerMain.getShop_name());
        tvAddress.setText(desingerMain.getLive_store_address());
        tvTime.setText(desingerMain.getShop_workingtime());

        initBanner(desingerMain.getPicture_img());

        FlowLayoutManager flowLayoutManager = new FlowLayoutManager();
        recycelrService.addItemDecoration(new SpaceItemDecoration(DensityUtil.dip2px(3)));
        recycelrService.setLayoutManager(flowLayoutManager);
        DesnigerShopAdapter desnigerShopAdapter = new DesnigerShopAdapter(desingerMain.getList());
        recycelrService.setAdapter(desnigerShopAdapter);

        if (desingerMain.getIs_redecorate() == 0) {
            btnChat.setVisibility(View.GONE);
        }
    }

    @Override
    protected void initData() {
        mFragmentList = new ArrayList<>();
        mList_title = new ArrayList<>();

        for (int i = 0; i < desingerMain.getCategory_list().size(); i++) {
            mList_title.add(desingerMain.getCategory_list().get(i).getCategory_name());
            mFragmentList.add(DesnigerFragment.newInstance(desingerMain.getCategory_list().get(i).getCategory_id(), desingerMain.getShop_id(), desingerMain.getShop_name()));

        }
        mHomeViewPagerAdapter = new HomeViewPagerAdapter(getSupportFragmentManager());
        viewpager.setAdapter(mHomeViewPagerAdapter);
//        ViewpagerLineUtil.setTabWidth(mTabLayout, 25);
        tabLayout.setupWithViewPager(viewpager);//
        mHomeViewPagerAdapter.setData(mFragmentList, mList_title);
        mHomeViewPagerAdapter.notifyDataSetChanged();
    }

    @Override
    protected void initEvents() {
        mButCancel.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                mPhotoDialog.dismiss();
            }
        });
        mButPhoto.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = null;

//                double mydout[] = bdToGaoDe(Double.valueOf(desingerMain.getLongitude()), Double.valueOf(desingerMain.getLatitude()));
                LngLat lngLat = new LngLat(Double.valueOf(desingerMain.getLongitude()), Double.valueOf(desingerMain.getLatitude()));
                LngLat mydout = CoodinateCovertor.bd_decrypt(lngLat);
                Uri uri = Uri.parse("amapuri://route/plan/?dlat=" + mydout.getLantitude() + "&dlon=" + mydout.getLongitude() + "&dname=" + desingerMain.getShop_name() + "&dev=0&t=0");
//                    Activity.startActivity(new Intent(Intent.ACTION_VIEW, uri));
                intent = new Intent(Intent.ACTION_VIEW, uri);
                startActivity(intent);
            }
        });
        mButOpen.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = null;
                Uri uri = Uri.parse("baidumap://map/direction?destination=latlng:" + desingerMain.getLatitude() + "," + desingerMain.getLongitude() + "|name:" + desingerMain.getShop_name() + "&mode=driving");
                intent = new Intent(Intent.ACTION_VIEW, uri);
                startActivity(intent);

            }
        });
        tvAddress.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.KITKAT) {
                    ToastUtil.getToastUtil().showShort("您的手机系统暂不支持该服务！");
                    return;
                }




//                PackageManager packageManager = getActivity().getPackageManager();

                if (isAvailable("com.autonavi.minimap")) {
//                    intent = packageManager.getLaunchIntentForPackage("com.autonavi.minimap")
                    mButPhoto.setVisibility(View.VISIBLE);

                }
                if (isAvailable("com.baidu.BaiduMap")) {
                    mButOpen.setVisibility(View.VISIBLE);
//                    intent = packageManager.getLaunchIntentForPackage("com.baidu.BaiduMap");

                }  if (!isAvailable("com.autonavi.minimap")&&!isAvailable("com.baidu.BaiduMap")){
                    ToastUtil.getToastUtil().showShort("手机暂无地图应用");
                    return;
                }

                BottomSheetUtil.collapsedDialog(mDialogView);
                mPhotoDialog.show();
//       else if (isAvailable("com.tencent.map")) {
////                    intent = packageManager.getLaunchIntentForPackage("com.tencent.map");
//                    Uri uri = Uri.parse("qqmap://map/routeplan?type=drive&to=" + desingerMain.getShop_name() + "&tocoord=" + desingerMain.getLatitude() + "," + desingerMain.getLongitude() + "&policy=2&referer=myapp");
//                    intent = new Intent(Intent.ACTION_VIEW, uri);
//                }
            }
        });

        mIvBack.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });

    }

    @Override
    public void initInject() {
        mMainComponent = DaggerMainActivityCompent.builder().applicationComponent(getApplicationComponent()).activityModule(getActivityModule()).build();
        mMainComponent.inject(this);
    }

    @Override
    protected int layoutResId() {
        return R.layout.activity_desniger_store;
    }

    @Override
    protected BasePresenter getPresenter() {
        return null;
    }

    @Override
    public void showLoading() {

    }

    @Override
    public void hideLoading() {

    }

    @Override
    public void error(String msg) {

    }

    @Override
    public void error(int code, String msg) {
        ToastUtil.getToastUtil().showShort(msg);
    }


    @Override
    public void getDesginerShopSuccess(List<DesingerMain> store) {

    }

    @Override
    public void getShopServiceSuccess(List<DesingerType> shopServices) {

    }

    @Override
    public void getStoreDetailSuccess(DesingerMain desingerMain) {

    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (data == null)
            return;
        switch (requestCode) {
            case MainActivity.REQUEST_GO_MALL:
                setResult(RESULT_OK, data);
                finish();
                break;

        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // TODO: add setContentView(...) invocation
        ButterKnife.bind(this);
    }

    @Override
    public MainActivityCompent getComponent() {
        return mMainComponent;
    }

    public boolean isAvailable(String mapPackageName) {
        PackageInfo packageInfo;
        try {
            packageInfo = getPackageManager().getPackageInfo(mapPackageName, 0);
        } catch (PackageManager.NameNotFoundException e) {
            packageInfo = null;
            e.printStackTrace();
        }
        return packageInfo == null ? false : true;
    }

    private void initBanner(List<String> commList) {
        List<LoopViewEntity> mListLoop = new ArrayList<>();
        for (int i = 0; i < commList.size(); i++) {
            LoopViewEntity entity = new LoopViewEntity();
            entity.setImageUrl(commList.get(i));
            entity.setDescript("");
            mListLoop.add(entity);
        }
        iv_head.setLoopData(mListLoop);
    }

    private double[] bdToGaoDe(double bd_lat, double bd_lon) {
        double[] gd_lat_lon = new double[2];
        double PI = 3.14159265358979324 * 3000.0 / 180.0;
        double x = bd_lon - 0.0065, y = bd_lat - 0.006;
        double z = Math.sqrt(x * x + y * y) - 0.00002 * Math.sin(y * PI);
        double theta = Math.atan2(y, x) - 0.000003 * Math.cos(x * PI);
        gd_lat_lon[0] = z * Math.cos(theta);
        gd_lat_lon[1] = z * Math.sin(theta);
        return gd_lat_lon;
    }
}
